import { HttpError, encryptPassword, randomSalt, toSuccess, useTransaction } from '@sker/core';
import { AutoUser } from '@sker/entities';
import { useData } from '@sker/runtime';
import { z } from 'zod';
/**
 * 账号及设备登录
 */
export default async () => {
    const input = z.object({
        password: z.string(),
        repassword: z.string(),
        realname: z.string(),
        token: z.string(),
        mobile: z.string(),
        max_count: z.number()
    });
    const body = input.parse(useData())
    if (body.repassword !== body.password) {
        throw new HttpError(`密码不一致`)
    }
    return await useTransaction(async m => {
        const fromUser = await m.findOne(AutoUser, { where: { token: body.token } });
        if (!fromUser) throw new HttpError(`参数错误`)
        const user = await m.findOne(AutoUser, { where: { mobile: body.mobile } })
        if (user) throw new HttpError(`用户已存在`)
        const salt = randomSalt();
        const password = await encryptPassword(body.password, salt)
        const createUser = m.create(AutoUser, {
            mobile: body.mobile,
            password: password,
            realname: body.realname,
            username: '',
            from: fromUser.mobile,
            salt,
            max_count: body.max_count,
            device_count: 0
        })
        await m.save(AutoUser, createUser)
        return toSuccess(true)
    })
}